<template>
  <el-container>
    <el-aside style="float:left;width: 300px;">
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <span>系统列表</span>
        </div>
        <div class="text item el-over-auto">
          <el-tree 
            :props="defaultProps"
            node-key="attId"
            ref="attachTree"
            @node-click="handleNodeClick"
            :load="loadNodeAttach"
            :default-expanded-keys="treeExpandedKey"
            :highlight-current="true"
            lazy
          ></el-tree>
        </div>
      </el-card>
    </el-aside>
    <el-main style="padding: 0 0 0 10px;">
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <span>
            <i class="el-icon-paperclip"></i> 附件管理
          </span>
        </div>
        <div  class="text item">
          <el-form :inline="true" :model="advancedQuerys" class="demo-form-inline" style="float: left;height:43px" @submit.native.prevent>
          <!-- 左侧搜索按钮 -->
          <el-form-item label="">
            <el-input clearable v-model="textSearch" placeholder="请输入附件名/业务编码/文件后缀 " style="width:288px;" @keyup.enter.native="attchList(1, 20)" @clear="attchList">
            <el-button slot="append" icon="el-icon-search" @click="attchList(1, 20)"></el-button>
          </el-input>
          </el-form-item>
          <!-- 右侧操作按钮 -->
          <el-form-item style="float:right">
            <el-button type="primary" plain @click="handleAdd">
              新增
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button type="danger" plain @click="handleBatchDel" v-show="delGroupAttachment">
              批量删除
              <i class="el-icon-delete"></i>
            </el-button>
          </el-form-item>
        </el-form>
          <el-table
            :data="attchTableData"
            height="100%"
            style="width: 100%"
            border
            ref="attchTablRef"
            stripe
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="90" prop="bigCatName" label="大类"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="100" prop="smallCatName" label="小类"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="100" prop="businessCode" label="业务编码"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="100" prop="attFullName" label="附件名"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="100" prop="attFileSuffix" label="文件后缀"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="100" prop="attFileSize" label="文件大小(kb)"></el-table-column>
            <el-table-column show-overflow-tooltip sortable min-width="100" prop="businessDesc" label="描述"></el-table-column>
            <el-table-column show-overflow-tooltip width="150" prop="control" align="center" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button class="td-btn-icon" type="text" icon="el-icon-download" title="下载" @click="handDownload(scope.$index, scope.row)"></el-button>
                <!-- <a :href='"/api/aggregation/attachManage/download/"+scope.row.attId' download>
                  <el-button class="td-btn-icon" type="text" icon="el-icon-download" title="下载"></el-button>
                </a> -->
                <el-button class="td-btn-icon" type="text" icon="el-icon-delete" title="删除" @click="handDelete(scope.$index, scope.row)"></el-button>
                <el-button class="td-btn-icon" type="text" icon="el-icon-view" :disabled="scope.row.attFileSuffix && !attFileSuffixObj[scope.row.attFileSuffix]" title="预览" @click="handSearch(scope.$index, scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>
<script>
import {Tree, Dialog, MessageBox, Message,TableColumn, Pagination, Tag,Table, Upload,Drawer} from 'element-ui'
import { findAttchList, getDomainAuth, findBigCat, findSmallCat, attachmentDelete, attachmentPrevie, attachmentDeleteBath } from '@/api/attachment/attachmentQuery/attachmentQuery.js'
export default {
  components: { //注册插件
    'el-tree': Tree, //树形菜单
    'el-dialog': Dialog, //弹窗
    "el-table-column": TableColumn, //表格列
    "el-pagination": Pagination, //分页
    'el-tag': Tag,
    "el-table": Table, //表格
    "el-upload":Upload, //上传
    'el-drawer': Drawer, //抽屉
  },
  data() {
    return {
      advancedQuerys:{},
      tableData:[
        {
          number:'',
          bigCatName:'销售预算',
          smallCatName:'预算计划',
          businessCode:'001',
          attFullName:'**文件',
          attFileSuffix:'.doc',
          attFileSize:'16'
        }
      ],
      defaultProps: {
        label: 'attFullName',
        isLeaf: 'isLeaf'
      },
      textSearch: '', //模糊搜索框
      attchTableData: [], // 附件查询列表数据
      pageSize: 20, // 显示页数
      currentPage: 1, // 当前展示页
      total: 0, // 总页数
      domainId: '', // 所属系统id
      treeExpandedKey: [], // 默认展开存储节点数据
      getCurrentData: {}, // 获取选中节点数据
      tableCheckboxData: [], // 存放选中表格数据数组
      attFileSuffixObj: { // 储存所有文件后缀名
        '.jpg':'.jpg',
        '.jpeg':'.jpeg',
        '.png':'.png',
        '.gif':'.gif',
        '.bmp':'.bmp',
        '.wbmp':'.wbmp',
        '.doc':'.doc',
        '.docx':'.docx',
        '.xlsx':'.xlsx',
        '.xls':'.xls',
        '.ppt':'.ppt',
        '.pptx':'.pptx',
        '.txt':'.txt',
        '.sql':'.sql',
        '.java':'.java',
        '.js':'.js',
        '.html':'.html',
        '.css':'.css',
        '.xml':'.xml',
        '.pdf':'.pdf'
      }
    }
  },
  computed: {
    delGroupAttachment () {
      if (this.tableCheckboxData && this.tableCheckboxData.length) return true
      else return false
    }
  },
  created() {
    // this.attchList(this.currentPage, this.pageSize)
    window.onresize = () => {
      this.$refs.attchTablRef.doLayout() //监听窗口变化，重绘表格布局
    }
  },
  methods:{
    // 选择表格复选框
    handleSelectionChange (val) {
      this.tableCheckboxData = val
    },
    // 附件查询列表
    attchList (currentPage = this.currentPage, pageSize = this.pageSize) {
      let bigCatId = ''
      let smallCatId = ''
      if (this.getCurrentData.attType === 'big') {
        bigCatId = this.getCurrentData.attId
      } else if (this.getCurrentData.attType === 'small') {
        smallCatId = this.getCurrentData.attId
      }
      findAttchList(currentPage, pageSize, {
        domainId: this.domainId,
        bigCatId: bigCatId,
        smallCatId: smallCatId,
        textSearch: this.textSearch
      }).then(res => {
        res.data.data.records.forEach(e => {
          e.attFileSize = (e.attFileSize/1024).toFixed(2)
        })
        this.attchTableData = res.data.data.records
        this.total = res.data.data.total || 0
        this.currentPage = currentPage || 1
        console.log(this.attchTableData)
        setTimeout(() => {
          this.$refs.attchTablRef.doLayout() //重绘表格宽度，解决表头对不齐的问题
        }, 0)
      })
    },
    // 树的点击事件
    handleNodeClick (data) {
      this.domainId = data.domainId
      this.getCurrentData = this.$refs.attachTree.getCurrentNode()
      this.attchList(this.currentPage, this.pageSize, this.domainId)
    },
    // 获取树数据
    loadNodeAttach (node, resolve) {
      if (node.level === 0) {
        getDomainAuth({
          domainName: "",
          domainCode: ""
        }).then(res => {
          let parentData = res.data.data
          parentData.forEach(e => {
            e.attFullName = e.domainName
            e.attId = e.domainId
            e.isLeaf = e.hasBigCat == "Y" ? false : true
          })
          resolve(parentData)
          console.log(parentData)
          this.domainId = parentData[0].domainId
          this.$refs.attachTree.setCurrentKey(this.domainId)
          this.treeExpandedKey = [this.domainId]
          this.attchList(this.currentPage, this.pageSize, this.domainId) // 表格初始化
        })
        .catch(res => {
          resolve([])
        })
      } else if (node.level === 1) { // 大类
        let domainId = node.data.domainId
        findBigCat(domainId).then(res => {
          let bigCatData = res.data.data
          bigCatData.forEach(e => {
            e.isLeaf = e.hasSmall == "Y" ? false : true
          })
          resolve(bigCatData)
        })
        .catch(res => {
          resolve([])
        })
      } else { // 小类
        let bigCatId = node.data.attId
        findSmallCat(bigCatId).then(res => {
          console.log(res)
          let smallCatData = res.data.data
          smallCatData.forEach(e => {
            e.isLeaf = e.hasSmall == "Y" ? false : true
          })
          resolve(smallCatData)
        })
          .catch(res => {
          resolve([])
        })
      }
    },
    //新增按钮
    handleAdd () {
      // let dynamicRouting = [{
      //   path: '/',
      //   component: this.pageLayout,
      //   meta: {
      //     title: '附件管理'
      //   },
      //   children: [
      //     {
      //       path: 'addattAchment',
      //       name: 'addattAchment',
      //       component: () => import('@/views/attachment/attachmentQuery/addattAchment'),
      //       meta: {
      //         title: '附件查询'
      //       }
      //     }
      //   ],
      // }]
      // this.$router.addRoutes(dynamicRouting)
      // this.$router.push({
      //   name: 'addattAchment'
      // })
      // this.multiRouters是全局提供的自动添加多级路由的方法
      this.$router.addRoutes(this.multiRouters([{
        path: 'addattAchment',
        name: 'addattAchment',
        component: () => import('@/views/attachment/attachmentQuery/addattAchment'),
        meta: {
          title: '附件查询'
        }
      }]))
      this.$router.push(this.routerMatch({
        name: 'addattAchment'
      }))
    },
    // 批量删除
    handleBatchDel () {
      MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delData()
      }).catch(() => {})
    },
    delData () {
      let attIds = [] // 存放选中附件表格当前行attid的数组
      this.tableCheckboxData.forEach(v => {
        attIds.push(v.attId)
      })
      attachmentDeleteBath(attIds).then(res => {
        if (res.data.code === 10000) {
          this.attchList()
        }
      })
    },
    // 下载按钮
    handDownload (index,row) {
      // 自定义form标签，初始化相关参数 
      var form = document.createElement("form")
      // var access_token = "d54e3ef7-6d69-4b4e-afb3-ef539cb80f9b"
      form.setAttribute("style", "display:none")
      form.setAttribute("method", "post")
      var params = {}
      // params.Authorization = access_token
      form.setAttribute("header", params)
      // var path = 'E:\\_ex_workplace\\zxsbWeb\\esgov-zxsb-zxsbweb\\src\\pages\\selfDetection.vue'
      var input = document.createElement('input')
      input.setAttribute('type', 'hidden')
      input.setAttribute('name', 'attId')
      input.setAttribute('value', row.attId)
      form.append(input)
      form.setAttribute("action", "/api/ccms/attachment/download")
      // form.setAttribute("target", "_blank")
      var body = document.createElement("body")
      body.setAttribute("style", "display:none")
      document.body.appendChild(form)
      form.submit()
      form.remove()
    },
    // 删除按钮
    handDelete (index,row) {
      MessageBox.confirm('是否确定要删除该行数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
			.then(() => {
				let attId = row.attId
        attachmentDelete(attId).then(res => {
          if (res.data.code === 10000) {
            this.attchList()
          }
        })
			})
			.catch(() => {})
    },
    // 预览按钮
    handSearch (index,row){
      let attId = row.attId
      attachmentPrevie(attId).then(res => {
        // console.log(res)
        if (res.data.code === 10000) {
          window.open(res.data.data)
        }
      })
    },
    // 每页条数
    handleSizeChange (val) {
      this.pageSize = val
      this.attchList()
    },
    // 当前页数
    handleCurrentChange (val) {
      this.currentPage = val
      this.attchList()
    }
  }
}
</script>
<style scoped></style>
